package pers.wwz.study.xmlhttphrequest.common.exceptionhandler;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.wwz.study.xmlhttphrequest.common.exception.BusinessException;
import pers.wwz.study.xmlhttphrequest.common.response.RestResult;

import javax.servlet.http.HttpServletRequest;

/**
 * 全局异常处理
 * TODO 定义异常枚举
 * TODO 数据库连接异常;redis连接异常;参数校验不合格异常等
 *
 */
@ControllerAdvice
public class GlobalExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


	/**
	 * 处理请求缺少参数异常
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value = MissingServletRequestParameterException.class)
	@ResponseBody
	public  RestResult BusinessExceptionHandler(HttpServletRequest req, MissingServletRequestParameterException e){
		logger.error("发生业务异常！原因是：{}",e.getCause());
		return RestResult.fail(-101,"缺少参数");
	}
	/**
	 * 处理自定义的业务异常
	 * @param req
	 * @param e
	 * @return
	 */
    @ExceptionHandler(value = BusinessException.class)
    @ResponseBody
	public  RestResult BusinessExceptionHandler(HttpServletRequest req, BusinessException e){
    	logger.error("发生业务异常！原因是：{}",e.getErrorMsg());
    	return RestResult.fail(e.getErrorCode(),e.getErrorMsg());
    }

	/**
	 * 处理空指针的异常
	 * @param req
	 * @param e
	 * @return
	 */
	@ExceptionHandler(value =NullPointerException.class)
	@ResponseBody
	public RestResult exceptionHandler(HttpServletRequest req, NullPointerException e){
		logger.error("发生空指针异常！原因是:",e);
		return RestResult.fail(-1,"空指针");
	}


    /**
	 * 处理其他异常
     * @param req
     * @param e
     * @return
     */
    @ExceptionHandler(value =Exception.class)
	@ResponseBody
	public RestResult exceptionHandler(HttpServletRequest req, Exception e){
    	logger.error("未知异常！原因是:",e);
       	return RestResult.fail(-999,"服务器内部错误");
    }
}
